<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\MessageSendService;
use Illuminate\Console\Command;

class SiteLocationNotConfirm extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:site-location-not-confirm';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开发经理对接客户15天未落址';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 获取从上线后指派开发经理15后未落址的数据发送飞书消息，只通知一次，来源-开店，状态-开店小程序 - 选址中状态 MissionTemplateEnum::SITE_STATUS
     */
    public function handle()
    {
        //获取通知的招商客服-config
        $notConfirmUser = json_decode(
            ConfigModel::query()
                ->where('module', 'openShopSiteLocation')
                ->where('name', 'notConfirmUser')
                ->value('value') ?? '', true
        );
        $sendNotConfirmUser = $notConfirmUser ? $notConfirmUser[0] : 0;
        $expiredAt = strtotime(date("Y-m-d H:i:s", strtotime("-15 Days")));//15天前
        if (config('app.env') == 'qa' || config('app.env') == 'dev' || config('app.env') == 'pre') {
            $expiredAt = time() - 2 * 60;//测试5分钟
        }
        $prodAt = ConfigModel::query()
                ->where('module', 'openShopSiteLocation')
                ->where('name', 'notConfirmProdTime')
                ->value('value') ?? '1671520487';//上线时间
        OpenShopSiteLocationModel::query()
            ->join('open_shop_site_mission', 'open_shop_site_mission.orderNo', '=', 'open_shop_site_locations.orderNo')
            ->join('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_site_locations.mainProcessId')
            ->with(['signOrderRel.identityCardRel', 'baseUserInfoRel'])
            ->where('open_shop_site_locations.developConsultantId', '>', 0)
            ->where('open_shop_site_locations.developConsultantFlagNotice', 0)
            ->where('open_shop_site_locations.source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
            ->where('open_shop_site_locations.siteStatus', '!=', OpenShopSiteLocationModel::SITE_STATUS_4)
            ->whereIn('open_shop_site_mission.stepStatus', MissionTemplateEnum::SITE_STATUS)
            ->where('open_shop_site_mission.status', SiteMissionEnum::STATUS_1)
            ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_2)
            ->where('open_shop_order_manager.updatedAt', '<', $expiredAt)
            ->where('open_shop_order_manager.updatedAt', '>', $prodAt)
            ->where('open_shop_order_manager.isDeleted', 0)
            ->where('open_shop_site_locations.isDeleted', 0)
            ->where('open_shop_site_mission.isDeleted', 0)
            ->select(
                [
                    'open_shop_site_locations.id', 'open_shop_site_locations.orderNo', 'open_shop_site_locations.cityArea', 'open_shop_site_locations.developConsultantId',
                    'open_shop_site_mission.stepStatus', 'open_shop_site_mission.createdAt'
                ]
            )
            ->groupBy('open_shop_site_locations.id')
            ->chunk(100, function ($item) use ($sendNotConfirmUser) {
                foreach ($item as $v) {
                    //加盟商姓名
                    $identityCardName = $v->signOrderRel && optional($v->signOrderRel)->identityCardRel ? optional(optional($v->signOrderRel)->identityCardRel)->name : "";
                    //开发经理姓名+手机号
                    $managerUid          = $v->developConsultantId ?? 0;
                    $userInfo            = collect($managerUid ? RmsUserRemote::getRmsUserByIds([$managerUid]) : [])->pluck(null, "id");
                    $managerUsername     = $userInfo->get($managerUid, [])["username"] ?? "";
                    $managerUserMobile   = $userInfo->get($managerUid, [])["mobile"] ?? "";
                    $managerFeishuUserId = $userInfo->get($managerUid, [])["feishuUserId"] ?? $sendNotConfirmUser;//飞书通知人消息
                    if (!$managerFeishuUserId) {//查询fs_user表的飞书user_id，user表飞书id可能查不到
                        $fsUserInfo = $userInfo->get($managerUid, [])['fs_user_rel'] ?? [];
                        if ($fsUserInfo && is_array($fsUserInfo)) {
                            $managerFeishuUserId = $fsUserInfo[0]['userId'] ?? "";
                        }
                    }
                    $desc                = vsprintf('%s门店15天内未落址，请及时联系开发经理<at id=%s></at>，核查原因', [optional($v->signOrderRel)->shopCode, $managerFeishuUserId]);
                    $data              = [
                        optional($v->signOrderRel)->shopCode,
                        $managerUsername . " " . $managerUserMobile,
                        $v->orderNo,
                        $v->cityArea,
                        $identityCardName . " " . optional($v->baseUserInfoRel)->mobile,
                        MissionTemplateEnum::STEP_STATUS_TEXT[$v->stepStatus],
                        $sendNotConfirmUser,
                        $v->createdAt->toDateTimeString(),
                        $desc,
                        BaseService::getOrderInfoWebAppUrl($v->orderNo),
                        optional($v->signOrderRel)->shopCode,
                    ];
                    $templateJson      = vsprintf(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteLocationNotConfirm.json')), $data);
                    //发布群里消息
                    SendFs::newRobot(SendFs::ROBOT_SITE_LOCATION_NOT_CONFIRM)->setCardMessageBody(json_decode($templateJson, true))->send();
                    //发给开发经理-个人
                    $desc         = vsprintf("%s门店15天内未落址，请及时联系<at id=%s></at>，协助核查原因", [optional($v->signOrderRel)->shopCode, $sendNotConfirmUser]);
                    $data         = [
                        optional($v->signOrderRel)->shopCode,
                        $managerUsername . " " . $managerUserMobile,
                        $v->orderNo,
                        $v->cityArea,
                        $identityCardName . " " . optional($v->baseUserInfoRel)->mobile,
                        MissionTemplateEnum::STEP_STATUS_TEXT[$v->stepStatus],
                        $managerFeishuUserId,
                        $v->createdAt->toDateTimeString(),
                        $desc,
                        BaseService::getSiteLocationAppletUrl(0, $v->orderNo),
                        optional($v->signOrderRel)->shopCode,
                    ];
                    $templateJson = vsprintf(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteLocationNotConfirm.json')), $data);
                    MessageSendService::sendMessage($managerFeishuUserId, 'user_id', json_decode($templateJson, true), 'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);

                    OpenShopSiteLocationModel::query()->where('id', $v->id)->update(['developConsultantFlagNotice' => 1]);//修改记录已发送飞书消息

                }
            });
    }
}
